package com.imooc.mq;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liansen
 * @create 04-04-10:32
 */
@Configuration
public class DelayConfig_Intustry {

    public static final String EXCHANGE_DELAY_REFRESH = "exchange_delay_refresh";

    public static final String QUEUE_DELAY_REFRESH = "queue_delay_refresh";

    public static final String DELAY_REFRESH_INDUSTRY = "delay.refresh.industry";

    //创建交换机
    @Bean(EXCHANGE_DELAY_REFRESH)
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_DELAY_REFRESH)
                .durable(true) //持久化
                .delayed() //设置延迟特性
                .build();
    }

    //创建队列
    @Bean(QUEUE_DELAY_REFRESH)
    public Queue queue(){
        return QueueBuilder.durable(QUEUE_DELAY_REFRESH)
                            .build();
    }

    //创建交换机和队列的绑定关系
    @Bean
    public Binding delayBindingIndustry(){
        /**
         * String destination,
         * DestinationType destinationType,
         * String exchange,
         * String routingKey,
         * @Nullable Map<String, Object> arguments
         */
        return new Binding(QUEUE_DELAY_REFRESH,
                Binding.DestinationType.QUEUE,
                EXCHANGE_DELAY_REFRESH,
                "delay.refresh.*",
                null);
    }

    //创建消息处理器,用来设置延迟的时间
    public static MessagePostProcessor setDelayTimes(Integer times){
        //匿名内部类
        return new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置持久属性
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                //设置延迟的时间, 单位毫秒
                message.getMessageProperties().setDelay(times);
                return message;
            }
        };
    }
}
